package com.hengxinyongli.iam.web.handler;


import com.hengxinyongli.iam.exception.AssertCheckException;
import com.hengxinyongli.iam.web.vo.Responses;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import static com.hengxinyongli.iam.web.vo.Responses.ERROR_CODE;

/**
 * @author magic
 * @date 2018/9/27/027 21:34
 * @version 1.0
 * Description ExceptionHandler
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Responses handlerArgumentValidException(MethodArgumentNotValidException exp) {
        BindingResult bindingResult = exp.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        String message = buildFieldErrorMessage(fieldError);
        return Responses.fail(ERROR_CODE,message);
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AssertCheckException.class)
    @ResponseBody
    public Responses handlerArgumentValidException(AssertCheckException exp) {
        return Responses.fail(ERROR_CODE,exp.getMessage());
    }


    private String buildFieldErrorMessage(FieldError fieldError) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append(fieldError.getField())
                .append(fieldError.getDefaultMessage());
        return stringBuilder.toString();
    }
}

